/*
 * Copyright 2007-2008 Michele Mostarda ( michele.mostarda@gmail.com ).
 * All Rights Reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package org.michelemostarda;

import java.util.Stack;

/**
 * Defines a composed entity with a begin and an end on the parsing stack.
 */
abstract class Marker {

    /**
     * Processes the stack with the collected lookahead, producing output on the emitter.
     *
     * @param converter
     * @param lookahead
     * @param stack
     * @param emitter
     * @return
     */
    abstract boolean processStack(Converter converter, String lookahead, Stack stack, Emitter emitter);

    /**
     * Emits the closure of a marker.
     *
     * @param emitter
     */
    abstract void emitClosure(Emitter emitter);

    /**
     * The marker has a look ahead longer than one char.
     * @return
     */
    abstract boolean mustLookAhead(String lookAhead);

    protected Marker removeMarker(Stack s, Class c) {
        for (int i = s.size() - 1; i >= 0; i--) {
            if (s.get(i).getClass().equals(c)) {
                return (Marker) s.remove(i);
            }
        }
        return null;
    }

    protected Marker removeMarker(Stack s) {
        return removeMarker(s, this.getClass());
    }

    protected Marker findMarker(Stack s, Class c) {
        Marker m;
        for (int i = s.size() - 1; i >= 0; i--) {
            m = (Marker) s.get(i);
            if (m.getClass().equals(c)) {
                return m;
            }
        }
        return null;
    }

    protected Marker findMarker(Stack s) {
        return findMarker(s, this.getClass());
    }

    protected boolean isSequenceOf(String s, char c) {
        for(Character cs : s.toCharArray()) {
            if(cs != c) {
                return false;
            }
        }
        return true;
    }


}
